package main

import (
	"flag"
	"gitee.com/yysf-xin/dproxy"
	"gitee.com/yysf-xin/dproxy/pkg/app"
	"gitee.com/yysf-xin/dproxy/pkg/tools"
	"gitee.com/yysf-xin/dproxy/pkg/v2ray"
	"golang.org/x/net/webdav"
	"net/http"
	"strings"
)

func main() {

	cfg := app.MaleDefault()
	flag.StringVar(&cfg.File.Addr, "addr", cfg.File.Addr, "listen address")
	flag.BoolVar(&cfg.File.EnableProxy, "proxy", cfg.File.EnableProxy, "enable proxy support")
	flag.BoolVar(&cfg.File.Db.Upgrade, "upgrade", cfg.File.Db.Upgrade, "upgrade db")
	flag.StringVar(&cfg.File.Db.DbName, "db", "", "db name default $HOME/.dproxy/dproxy.db")
	flag.BoolVar(&cfg.File.Log.Router, "log_router", cfg.File.Log.Router, "debug print router")
	flag.StringVar(&cfg.FileName, "config", "", "config file default $HOME/.dproxy/dproxy.yml")

	flag.Var(&cfg.File.V2ray, "v2fly", cfg.File.V2ray.String())

	dir := &cfg.File.Server.Dir
	flag.StringVar(&dir.Dir, "dir", "", "only start a local dir server http server")
	flag.StringVar(&dir.Path, "path", "/", "only start a local http server path")

	flag.StringVar(&cfg.File.Ssl.Cert, "ssl_crt", "ca.crt", "ssl crt")
	flag.StringVar(&cfg.File.Ssl.Key, "ssl_key", "ca.key", "ssl key")

	//v2rayCfg := &cfg.File.V2ray
	//flag.StringVar(&v2rayCfg.Addr,"fly_addr", "0.0.0.0:8888","v2ray http listen addr")
	//flag.StringVar(&v2rayCfg.Protocol,"fly_protocol", "http","v2ray listen protocol")

	_, err := app.NewConfigFile(cfg)
	if err != nil {
		tools.Log.Fatal(err)
		return
	}
	// start a local server
	if dir.Dir != "" {

		dav := &webdav.Handler{
			Prefix:     dir.Path,
			FileSystem: webdav.Dir(dir.Dir),
			LockSystem: webdav.NewMemLS(),
		}
		f := http.FileServer(http.Dir(dir.Dir))
		if dir.Path != "/" {
			if strings.HasSuffix(dir.Path, "/") {
				f = http.StripPrefix(dir.Path, f)
			}
		}
		http.HandleFunc(dir.Path, func(w http.ResponseWriter, r *http.Request) {
			if r.Method == "GET" {
				a := r.Header.Get("Accept")
				if a != "" && strings.Contains(a, "text/html") {
					f.ServeHTTP(w, r)
				}
			}
			dav.ServeHTTP(w, r)
		})

		tools.Log.Println("start local http dir server", cfg.File.Addr, dir.Path, dir.Dir)
		err = http.ListenAndServe(cfg.File.Addr, nil)
		if err != nil {
			tools.Log.Println(err)
		}
		return
	}
	s, err := dproxy.NewServer(cfg)

	if err == nil {
		err = s.ListenAndServe()
	}
	if err != nil {
		tools.Log.Println(err)
	}
}

func startV2ray(cfg *app.Config) {
	s, err := v2ray.NewServer(cfg)
	if err != nil {
		tools.Log.Println(err)
	}
	err = s.Start()
	if err != nil {
		tools.Log.Println(err)
	}
}
